const mongoose = require("mongoose");

// 获取用户订单
const getUserOrder = async (id) => {
    const orderModel = mongoose.model("order");
    const seatsModel = mongoose.model("seatings");
    const schedulesModel = mongoose.model("schedules");
    let data = await orderModel.find({
        userId: id
    }) //按照订单id进行排序
    for (let i = 0; i < data.length; i++) {
        for (let j = 0; j < data[i].seatingsId.length; j++) {
            // 拿到拍片id
            data[i].schedulesId = await schedulesModel.findOne({
                _id: data[i].schedulesId
            }).populate('cinemasId').populate('movieId').populate('theaterId')
            data[i].seatingsId[j] = await seatsModel.find({
                _id: data[i].seatingsId[j]
            }).populate('seatId')
        }
    }
    return data;

}
// 按页数获取用户订单
const getUserOrderPage = async ({
    userId,
    curPage,
    eachPage
}) => {
    // 将页数和每页显示的条数转化为数字
    (curPage = curPage - 0), (eachPage = eachPage - 0);
    // 定义一个该用户的数据信息
    const data = {
        total: 0,
        maxPage: 0,
        curPage: curPage,
        eachPage: eachPage
    }
    // 获取所需要的modul
    const orderModel = mongoose.model("order");
    const seatsModel = mongoose.model("seatings");
    const schedulesModel = mongoose.model("schedules");
    // 查找数据的总数
    data.total = await orderModel.find({
        userId,seeState:1
    }).countDocuments();
    // 根据数据总数来设置总共的页数
    data.maxPage = Math.ceil(data.total / eachPage);
    // 根据页数和每页显示的条数来计算查询的时候要跳转的数据条数
    let skipNum = (data.curPage - 1) * eachPage;

    data.rows = await orderModel.find({
        userId,seeState:1
    }).sort({_id:-1}).skip(skipNum).limit(eachPage).exec()
    //按照订单id进行排序
    for (let i = 0; i < data.rows.length; i++) {
        for (let j = 0; j < data.rows[i].seatingsId.length; j++) {
            // 拿到拍片id
            data.rows[i].schedulesId = await schedulesModel.findOne({
                _id: data.rows[i].schedulesId
            }).populate('cinemasId').populate('movieId').populate('theaterId')
            data.rows[i].seatingsId[j] = await seatsModel.find({
                _id: data.rows[i].seatingsId[j]
            }).populate('seatId')
        }
    }
    return data;

}
// 删除订单
const delOder = async (id) => {
    const orderModel = mongoose.model("order");
    // console.log(id);
    let data = await orderModel.updateOne({_id: id.id},{seeState:0}) //按照订单id进行排序
    return data;

}


module.exports = {
    // getOrder,
    getUserOrder,
    getUserOrderPage,
    delOder
};